<template>
	<view class="content">
		<view style="width: 10px;">头部</view>
		<view style="margin-top: 100px;margin-left: 10px;margin-right: 10px;display: flex;flex-direction: row;">
			<view style="width: 10px;"></view>
			<view style="flex:1;background-color: yellow;border: 10px solid pink;">
				<canvas type="webgl" id="canvasBox" :style="{width: screenWidth+'px', height: screenWidth+'px',}"
					@touchstart="touchStart" @touchmove="touchMove" @touchend="touchEnd"></canvas>
			</view>
			<view style="width: 10px;"></view>
		</view>
	</view>
</template>

<script>
	// import * as THREE from '../../static/threejs/libs/three.weapp.js'
	// import {
	// 	OrbitControls
	// } from '../../static/threejs/jsm/controls/OrbitControls'


	let camera = null
	let AllMeshArr = [] //所有的字母
	let chooseMesh = null
	let chooseMeshArr = [] //选中的物体
	let selectedPositionArr = [] //选中的字母
	let selectedLetterArr = [] //选中的位置
	let isGestureStarted = false
	export default {
		data() {
			return {
				title: 'game游戏',
				screenWidth: 0
			}
		},
		onLoad() {
			// 数组中随机获取一个元素
			function getRandomLetter() {
				var letters_26 = [
					"a", "b", "c", "d", "e", "f", "g",
					"h", "i", "j", "k", "l", "m", "n",
					"o", "p", "q", "r", "s", "t", "u",
					"v", "w", "x", "y", "z"
				];
				var randomIndex = Math.floor(Math.random() * letters_26.length); // 生成一个随机索引值
				return letters_26[randomIndex]; // 根据随机索引值获取相应位置上的元素
			}
			const guiParams = {
				fontColor: '#ffffff', // 字体颜色
				backgroundColor: '#fff000', // 背景颜色
				selectedFontColor: '#0000ff', // 选中的字体颜色
				selectedBackgroundColor: '#00ffff', // 选中的背景颜色
				rows: 7, //宫格行数
				cols: 7, //宫格列数
				spacing: 10, // 精灵模型之间的间距
			};

			var lettersObj = {
				// "00": "a",
				// "01": "a",
			};
			var lettersObj = {};
			for (var i = 0; i < guiParams.rows; i++) {
				for (var j = 0; j < guiParams.cols; j++) {
					lettersObj[i.toString() + j.toString()] = getRandomLetter();
				}
			}
			this.screenWidth = uni.getSystemInfoSync().windowWidth - 40;

			uni.createSelectorQuery().select('#canvasBox').fields({
				node: true,
				size: true
			}).exec((res) => {

				let canvas = res[0].node;
				let canvasId = res[0].node._canvasId
				canvas.width = this.screenWidth;
				canvas.height = this.screenWidth;

				// 模型大小
				var spriteWidth = (this.screenWidth) / guiParams.cols; // 模型的宽度  

				// 其他绘制操作...
				console.log("res========================")
				console.log(res)

				canvas = THREE.global.registerCanvas(canvasId, canvas)

				// 场景
				const scene = new THREE.Scene();
				scene.background = new THREE.Color(0xAAAAAA);

				// 渲染器
				const renderer = new THREE.WebGLRenderer({
					antialias: true
				});
				// 获取设备像素比
				uni.getSystemInfo({
					success: function(res) {
						const pixelRatio = res.pixelRatio;
						renderer.setPixelRatio(pixelRatio);
					}
				});

				//相机
				camera = new THREE.OrthographicCamera(
					this.screenWidth / -2,
					this.screenWidth / 2,
					this.screenWidth / 2,
					this.screenWidth / -2, 1, 1000
				);
				camera.position.set(0, 0, 700);
				camera.lookAt(0, 0, 700);

				//辅助观察的坐标系
				const axesHelper = new THREE.AxesHelper(100);
				scene.add(axesHelper);

				//光源设置
				const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
				directionalLight.position.set(100, 60, 50);
				scene.add(directionalLight);
				const ambient = new THREE.AmbientLight(0xffffff, 0.4);
				scene.add(ambient);

				// 创建宫格
				for (let i = 0; i < guiParams.cols; i++) {
					for (let j = 0; j < guiParams.cols; j++) {
						let currentLetter = lettersObj[i.toString() + j.toString()];

						const geometry = new THREE.CircleGeometry(spriteWidth / 2 - guiParams.spacing /
							2, 32);
						const texture = new THREE.TextureLoader().load('./pikachu.png');
						const material = new THREE.MeshBasicMaterial({
							// map: texture,
							color: 0x00ff00
						});
						const mesh = new THREE.Mesh(geometry, material);
						mesh.position.set((j - Math.floor(guiParams.rows / 2)) * (spriteWidth),
							(i - Math.floor(guiParams.rows / 2)) * (spriteWidth),
							10); // 将平面放置在 x=1, y=2, z=3 的位置


						// 创建字体加载器
						const fontLoader = new THREE.FontLoader();
						// 加载字体文件
						fontLoader.load(
							'https://ftalk.soullions.com/threejs/fonts/helvetiker_bold.typeface.json',
							function(res) {
								// 在这里可以访问加载的字体数据
								const font = new THREE.TextBufferGeometry(currentLetter, {
									font: res,
									size: 20,
									height: 1
								});

								font.computeBoundingBox();

								// 创建字母的材质
								const textMaterial = new THREE.MeshBasicMaterial({
									color: 0xff0000
								});

								// 创建字母的网格对象
								const textMesh = new THREE.Mesh(font, textMaterial);
								textMesh.userData.type = '字母'; //设置类型

								// 将字体模型的位置调整为居中
								const textBoundingBox = new THREE.Box3().setFromObject(textMesh);
								const textWidth = textBoundingBox.max.x - textBoundingBox.min.x;
								const textHeight = textBoundingBox.max.y - textBoundingBox.min.y;
								textMesh.position.x = -textWidth / 2;
								textMesh.position.y = -textHeight / 2;

								// 将字母添加到平面上
								mesh.add(textMesh);
							})

						// 设置自定义属性
						mesh.userData.letter = currentLetter; //设置字母
						mesh.userData.position = i.toString() + j.toString(); //设置位置
						mesh.userData.type = '平面'; //设置类型

						AllMeshArr.push(mesh);
						scene.add(mesh);
					}
				}

				function render() {
					canvas.requestAnimationFrame(render);
					renderer.render(scene, camera);
				}

				render()

			});
		},
		methods: {
			touchStart(e) {
				console.log('canvas:touchStart', e)
				// THREE.global.touchEventHandlerFactory('canvas', 'touchstart')(e)
				isGestureStarted = true
			},

			touchMove(e) {
				// THREE.global.touchEventHandlerFactory('canvas', 'touchmove')(e)
				if (isGestureStarted) {
					// 处理触摸移动事件
					var touch = e.touches[0];
					var Sx = touch.x; //鼠标单击位置横坐标
					// var Sy = touch.y - 50; //鼠标单击位置纵坐标【手机端需要减去margin-top的值】
					var Sy = touch.y; //鼠标单击位置纵坐标【手机端需要减去margin-top的值】
					// console.log('Sx:', Sx)
					// console.log('Sy:', Sy)
					//屏幕坐标转WebGL标准设备坐标
					var x = (Sx / this.screenWidth) * 2 - 1; //WebGL标准设备横坐标
					var y = -((Sy) / this.screenWidth) * 2 + 1; //WebGL标准设备纵坐标
					//创建一个射线投射器`Raycaster`
					var raycaster = new THREE.Raycaster();
					//通过鼠标单击位置标准设备坐标和相机参数计算射线投射器`Raycaster`的射线属性.ray
					raycaster.setFromCamera(new THREE.Vector2(x, y), camera);
					//返回.intersectObjects()参数中射线选中的网格模型对象
					// 未选中对象返回空数组[],选中一个数组1个元素，选中两个数组两个元素
					var intersects = raycaster.intersectObjects(AllMeshArr);
					if (intersects.length > 0) {
						chooseMesh = intersects[0].object;
						var result = selectedPositionArr.includes(chooseMesh.userData.position);
						if (!result) {
							chooseMeshArr.push(chooseMesh)
							selectedPositionArr.push(chooseMesh.userData.position);
							selectedLetterArr.push(chooseMesh.userData.letter);

							this.onSpriteSelected(chooseMesh);
						}
					}
				}
			},

			touchEnd(e) {
				console.log('canvas:touchEnd', e)
				// THREE.global.touchEventHandlerFactory('canvas', 'touchend')(e)

				if (isGestureStarted) {
					isGestureStarted = false
				}
			},

			// 选中精灵模型的事件处理函数
			onSpriteSelected(chooseMesh) {
				console.log('选中精灵模型的事件处理函数', chooseMesh)
				chooseMesh.material.color.set(0x00ffff);
				console.log('chooseMesh=', chooseMesh)

				// 遍历PlaneGeometry的子对象
				chooseMesh.children.forEach(child => {
					// 判断子对象是否是字体模块
					console.log('child=', child)
					if (child.userData.type === '字母') {
						// 恢复字体模块的颜色
						child.material.color.set(0xffffff);
					}
				});
			},
		}
	}
</script>

<style>
	page {
		overflow: hidden;
	}

	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	#canvasBox {
		background-color: red;
		margin: 0 auto;
	}

	.logo {
		height: 200rpx;
		width: 200rpx;
		margin-top: 200rpx;
		margin-left: auto;
		margin-right: auto;
		margin-bottom: 50rpx;
	}

	.text-area {
		display: flex;
		justify-content: center;
	}

	.title {
		font-size: 36rpx;
		color: #8f8f94;
	}
</style>